package com.phkj.qdh.ui.dialog

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.base.BaseDialogFragment
import com.phkj.qdh.bean.Detail
import com.phkj.qdh.bean.KeyPointData
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.DialogSelectKeyPonitBinding
import com.phkj.qdh.ui.adapter.CommonSelectAdapter
import com.phkj.qdh.ui.adapter.CommonSelectBean
import com.phkj.qdh.ui.adapter.KeyPointSelectAdapter
import com.phkj.qdh.ui.fragment.teaminspect.TeamInspectVM
import com.phkj.qdh.ui.fragment.teaminspect.getTeamInspectVMProvider
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 基础选择
 */
class SelectKeyPonitDialog : BaseDialogFragment() {
    private var param1: Int? = null
    private var param2: String? = null
    private var _binding: DialogSelectKeyPonitBinding? = null
    private val pageInfo = PageInfo()
    private lateinit var helper: QuickAdapterHelper
    private val keyPointSelectAdapter by lazy { KeyPointSelectAdapter() }

    private val tempData = ArrayList<KeyPointData>()
    private val binding get() = _binding!!
    private lateinit var vm: TeamInspectVM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getInt(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = DialogSelectKeyPonitBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getTeamInspectVMProvider())[TeamInspectVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            tvTitle.text = param2?:""
            rvItem.run {
                layoutManager = LinearLayoutManager(requireContext())

            }
            btnConfirm.setOnClickListener {
                val data = keyPointSelectAdapter.items.filter { it.isSelected }
                if (data.isNullOrEmpty()) {
                    ToastUtils.show("请选择${param2}")
                    return@setOnClickListener
                }
                var pos = 0
                keyPointSelectAdapter.items.forEachIndexed { index, commonSelectBean ->
                    if (commonSelectBean.isSelected) {
                        pos = index
                    }
                }
                parentFragmentManager.setFragmentResult(
                    "key", bundleOf("data" to tempData.get(pos))
                )
                this@SelectKeyPonitDialog.dismiss()
            }
        }

        helper = QuickAdapterHelper.Builder(keyPointSelectAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    pageInfo.nextPage()
                    getData()
                }

                override fun onFailRetry() {
                    getData()
                }

                override fun isAllowLoading(): Boolean {
                    return true
                }
            }).build()

        binding.rvItem.adapter = helper.adapter

        launchAndRepeatWithViewLifecycle {
            vm.keyPointDataList.collectLatest {
//                if (pageInfo.isFirstPage) {
//                    keyPointSelectAdapter.submitList(it)
//                } else {
//                    keyPointSelectAdapter.addAll(it)
//                }
//
//                if (it.size != PAGE_SIZE) {
//                    helper.trailingLoadState = LoadState.NotLoading(true)
//                } else {
//                    helper.trailingLoadState = LoadState.NotLoading(false)
//                }
                val selectData = ArrayList<CommonSelectBean>()
                it.forEach { b ->
                    b.keyPointFieldBaseVOList.forEach { c ->
                        if (c.fieldName.equals("名称")||c.fieldName.equals("姓名")) {
                            selectData.add(CommonSelectBean(c.fieldValue, false))
                        }
                    }
                }
                if (pageInfo.isFirstPage) {
                    keyPointSelectAdapter.submitList(selectData)
                    tempData.clear()
                    tempData.addAll(it)
                } else {
                    keyPointSelectAdapter.addAll(selectData)
                    tempData.addAll(it)
                }

                if (it.size != PAGE_SIZE) {
                    helper.trailingLoadState = LoadState.NotLoading(true)
                } else {
                    helper.trailingLoadState = LoadState.NotLoading(false)
                }


            }
        }
        keyPointSelectAdapter.setOnItemClickListener { adapter, _, pos ->
            adapter.items.forEachIndexed { index, keyPointDataBean ->
                if (index == pos) {
                    keyPointDataBean.isSelected = true
                } else {
                    keyPointDataBean.isSelected = false
                }
            }
            adapter.notifyItemRangeChanged(0, adapter.itemCount)
        }

        getData()
    }

    fun getData() {
        val map = HashMap<String, Any?>()
        map["size"] = PAGE_SIZE
        map["page"] = pageInfo.page
        map["keyPointTypeId"] = param1
        vm.getKeypointDataList(map)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Int, param2: String) = SelectKeyPonitDialog().apply {
            arguments = Bundle().apply {
                putInt(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}